module pwm_generator

#(parameter N=10, START_SPEED = 100)

(

    // global clock and asyn reset

    input CLOCK_50,

    input RST_N,

    // clock enable tick

    input clock_enable,

    // PWM interface

    input adjust_enable,

    input [N:1] period,

    output reg pwm_out

);

reg [N:1] period_r;

reg [N:1] pulse_width_r;

// pass the parameter

always@(posedge CLOCK_50, negedge RST_N)

    if(!RST_N)    begin

        period_r <= START_SPEED;

        pulse_width_r <= START_SPEED >> 1;

    end

    else if(adjust_enable) begin

        period_r <= period;

        pulse_width_r <= period >> 1;

    end

// counter

reg [N:1] cnt;   

always@(posedge CLOCK_50, negedge RST_N)

    if(!RST_N) cnt <= 0;

    else if(clock_enable) begin

        if(cnt == period_r) cnt <= 0;

        else cnt <= cnt + 1'b1;

    end

// generate pulse   

always@(posedge    CLOCK_50, negedge RST_N)

    if(!RST_N) pwm_out <= 0;

    else if(clock_enable) begin

        if(cnt < pulse_width_r) pwm_out <= 1;

        else pwm_out <= 0;

    end

endmodule